package com.miluGame.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.miluGame.util.Util;

/**
 * Servlet Filter implementation class CommonFilter
 */
public class CommonFilter implements Filter {
      
	private String[] passUrls = new String[]{"login"};
    /**
     * @see Filter#Filter()
     */
    public CommonFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String url = req.getRequestURI();
		if (url != null) {
			// 跳过不需要过滤验证的资源
			boolean pass = false;
			if (passUrls != null) {
				for (String suffix : passUrls) {
					if (url.endsWith(suffix)) {
						pass = true;// 需要跳过
						break;
					}
				}
			}
			
			if (!pass) { // 如果需要过滤
				HttpServletResponse resp = (HttpServletResponse) response;
				Object user = req.getSession().getAttribute("user");
				if(user == null){
					//Util.jump(resp, req.getContextPath()+"login.jsp");
					resp.sendRedirect(req.getContextPath()+"/login.jsp"); // 没有登录
					//req.getRequestDispatcher("../../login.jsp").forward(request,response);
				}else{
					chain.doFilter(request, response);
				}
			}else{
				chain.doFilter(request, response);
			}
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		String configPassUrls = fConfig.getInitParameter("passUrls");
		if (configPassUrls != null) {
			configPassUrls = configPassUrls.replace(" ", "");
			passUrls = configPassUrls.split(",");
			
		}
	}

}
